import {
  VuexModule,
  Module,
  Mutation,
  Action,
  getModule,
} from 'vuex-module-decorators'
import store from '@/store'

export interface ISendEmailSettingsState {
  title: string
  replyEmail: string
  minSendInterval: number
  maxSendInterval: number
  sendMethod: number
  sendTemplateMethod: number
  trackReadStatus: boolean
  userId: number
}

@Module({ dynamic: true, store, name: 'sendEmailSettings' })
class SendEmailSettings extends VuexModule implements ISendEmailSettingsState {
  title: string
  replyEmail: string
  minSendInterval: number
  maxSendInterval: number
  sendMethod: number
  sendTemplateMethod: number
  trackReadStatus: boolean
  userId: number

  @Mutation
  private CHANGE_SEND_EMAIL_SETTING(payload: ISendEmailSettingsState) {
    this.title = payload.title
    this.replyEmail = payload.replyEmail
    this.minSendInterval = payload.minSendInterval
    this.maxSendInterval = payload.maxSendInterval
    this.sendMethod = payload.sendMethod
    this.sendTemplateMethod = payload.sendTemplateMethod
    this.trackReadStatus = payload.trackReadStatus
  }

  @Action
  public ChangeSendEmailSetting(payload: ISendEmailSettingsState) {
    this.CHANGE_SEND_EMAIL_SETTING(payload)
  }

  @Action
  public InitSendEmailSetting(userId: number) {
    const settingStr = localStorage.getItem(`sendEmailSettings_${userId}`)

    if (settingStr) {
      const setting = JSON.parse(settingStr)
      this.CHANGE_SEND_EMAIL_SETTING({ ...setting, userId })
    } else {
      this.CHANGE_SEND_EMAIL_SETTING({
        title: '营销任务',
        replyEmail: '',
        minSendInterval: 2,
        maxSendInterval: 5,
        sendMethod: 0,
        sendTemplateMethod: 0,
        trackReadStatus: true,
        userId,
      })
    }
  }
}

export const SendEmailSettingsModule = getModule(SendEmailSettings)
